package com.lifep.collect.platform.module;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.lifep.collect.platform.collect.Collector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.function.Function;

/**
 * @author: zw
 * @create: 2024-09-28 22:14
 * @description:
 **/
@Slf4j
public class DmcSpringModule implements DmcModule {
    /**
     * 模块的名称，数据提供者
     */
    private final String dataProvider;
    /**
     * 模块中的Collector，Key为Category
     */
    private final Map<String, Collector> collectors;
    /**
     * 上下文
     */
    private final ApplicationContext applicationContext;

    public DmcSpringModule(String dataProvider, ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        this.dataProvider = dataProvider;
        this.collectors = scanComponent(applicationContext, Collector.class,
                Collector::getCategory);
    }

    private <T> Map<String, T> scanComponent(ApplicationContext applicationContext, Class<T> type, Function<T, String> keyFunction) {
        Map<String, T> collectMap = Maps.newHashMap();
        // 获取jar包中接口类的实现，并加入到缓存中
        applicationContext.getBeansOfType(type).values().forEach(component -> {
            String category = keyFunction.apply(component).toUpperCase();
            collectMap.put(category, component);
        });

        return ImmutableMap.copyOf(collectMap);
    }


    @Override
    public Collector getCollector(String category) {
        return collectors.get(category);
    }

    @Override
    public String getName() {
        return dataProvider;
    }

    @Override
    public void destroy() {
    }

    @Override
    public ClassLoader getChildClassLoader() {
        return this.applicationContext.getClassLoader();
    }
}
